package com.lihao.wanandroid.ui.home.recommend

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.lihao.jetpackcore.base.BaseViewModel
import com.lihao.jetpackcore.ext.request
import com.lihao.jetpackcore.state.ResultState
import com.lihao.wanandroid.app.network.callback.ListDataUiState
import com.lihao.wanandroid.data.model.ArticleResponse
import com.lihao.wanandroid.data.AppRepository
import com.lihao.wanandroid.data.model.BannerResponse

/**
 * Created by lihao on 2020/5/20.
 * Describe: 首页文章列表ViewModel
 */
class RecommendViewModel(application: Application) : BaseViewModel(application) {

    var pageNo: Int = 0

    var homeDataState: MutableLiveData<ListDataUiState<ArticleResponse>> = MutableLiveData()

    var bannerData: MutableLiveData<ResultState<ArrayList<BannerResponse>>> = MutableLiveData()

    fun getHomeData(isRefresh: Boolean) {
        if (isRefresh) {
            pageNo = 0
        }
        request({ AppRepository.getHomeData(pageNo) }, {
            // 请求成功
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.datas
            )
            homeDataState.postValue(listDataUiState)
        }, {
            // 请求失败
            val listDataUiState = ListDataUiState(
                isSuccess = false,
                errorMsg = it.errorMsg,
                isRefresh = isRefresh,
                listData = arrayListOf<ArticleResponse>()
            )
            homeDataState.postValue(listDataUiState)
        })
    }

    fun getBannerData() {
        request({AppRepository.getHomeBanner()}, bannerData)
    }
}